var express = require('express');
const {default: mongoose} = require('mongoose');
const {v4: uuidv4} = require('uuid');
var router = express.Router();
var recommend = require('../models/recommend');
var movie = require('../models/movie');
var article = require('../models/article');
var user = require('../models/user');

/* GET home page. */
router.get('/', function (req, res, next) {
    res.render('index', {title: 'Express'});
});


router.get('/test', function (req, res, next) {
    mongoose.connect('mongodb://root:root@localhost:27017/pets?authSource=admin');
    mongoose.Promise = global.Promise;

    var Cat = mongoose.model('cat', {name: String});

    var tom = new Cat({name: "Tom"});
    tom.save()
        .then(doc => {
            console.log('insert success!' + doc);
        })
        .catch(err => {
            console.log(err);
        });
    res.send('数据库连接测试');
});

//显示主页的推荐大图等
router.get('/showIndex', async function (req, res, next) {
    try {
        var recommends = await recommend.findAll()
        res.json({status: 0, message: "获取推荐", data: recommends})
    } catch (err) {
        console.log(err);
        res.status(500).json({status: 1, message: "获取主页推荐失败"});
    }
});
//显示所有的排行榜，也就是对于电影字段index的样式
router.get('/showRanking', async function (req, res, next) {
    try {
        var getMovies = await movie.find({movieMainPage: true});
        res.json({status: 0, message: "获取主页", data: getMovies})
    } catch (err) {
        console.log(err);
        res.json({status: 1, message: "获取主页失败" + err})
    }
});

//显示文章列表
router.get('/showArticle', async function (req, res, next) {
    try {
        var articles = await article.findAll();
        res.json({status: 0, message: "获取主页文章成功", data: articles});
    } catch {
        res.status(500).json({status: 1, message: "获取主页文章失败"});
    }
});

//显示文章的内容
router.get('/articleDetail', async function (req, res, next) {
    try {
        if (!req.query.articleId || typeof req.query.articleId !== 'string' || req.query.articleId.trim() === '') {
            res.json({status: 1, message: '文章id出错'})
            return;
        }
        const getArticle = await article.findByArticleId(req.query.articleId);
        if (!getArticle) {
            res.json({status: 0, message: "获取失败"});
            return;
        }
        res.json({status: 1, message: '获取成功', data: getArticle});
    } catch (err) {
        console.error(`Error fetching article: ${err.message}`, {errorId: uuidv4()});
        res.json({status: STATUS_ERROR, message: '服务器错误', errorId: uuidv4()});
    }
});

//显示用户自己个人信息的内容
router.get('/showUser', function (req, res, next) {
    try {
        if (!req.body.user_id) {
            res.json({status: 1, message: "用户状态出错"})
        }
        const getUser = user.findById(req.body.user_id)
        res.json({
            status: 0, message: "获取成功", data: {
                user_id: getUser._id,
                username: getUser.username,
                userMail: getUser.userMail,
                userPhone: getUser.userPhone,
                userStop: getUser.userStop
            }
        })

    } catch (err) {
        console.log(err);
    }
})

router.get('/movie-detail', (req, res) => {
    movie.findById(req.query.id)
        .then((data) => {
            res.json({status: 0, message: '获取成功', data: data});
        }).catch((error) => {
        console.log(error);
        res.json({status: 1, message: '查询失败'});
    });
});

router.post('/movie/support/:id', (req, res) => {
    movie.findOneAndUpdate({_id: req.params.id}, {$inc: {movieNumSuppose: 1}}, {returnOriginal: false})
        .then((result) => {
            res.json({status: 0, message: '点赞成功', data: result});
        })
        .catch((error) => {
            res.json({status: 1, message: '点赞失败,错误信息为: ' + error});
        })
});

router.get('/movie/downloadUrl/:id', (req, res) => {
    movie.findById(req.params.id)
        .then((result) => {
            res.json({status: 0, message: '获取下载地址', data: result.movieDownload});
        })
        .catch((error) => {
            res.json({status: 1, message: '获取下载地址失败,错误信息为:' + error});
        });
});

module.exports = router;
